<template>
  <div class="chat_list">
    <div class="head">
      <nut-navbar class="navbar" z-index="5" :clickable="false" fixed>
        <template #content>
          <span>{{ t('chat_page_chat_list') }}({{ state.chatitemList?.length || 0 }})</span>
        </template>
        <template #left>
          <ImgT @click="goBack()" class="close" src="/imgs/serviceModal/goback.webp" alt="" />
        </template>
        <template #right>
          <iconpark-icon @click="router.push('/friendsList')" class="close" icon-id="liaotlbren"
            size="1.5rem"></iconpark-icon>
        </template>
      </nut-navbar>
    </div>
    <div class="section">
      <div class="groups">
        <div class="groups_tabs">
          <scroll-view class="scroll-view" :scroll-x="true" style="width: 100%; white-space: nowrap;display: flex;">
            <view class="item" :class="active == 0 ? 'active' : ''" @click="selectTab(0)"> {{ t('all') }} </view>
            <view class="item" v-for="(item, index) in state.groupList" :key="index"
              :class="active == index + 1 ? 'active' : ''" @click="selectTab(index + 1, item)">
              {{ item.name }}
            </view>
          </scroll-view>
        </div>
        <div class="group_setting">
          <ImgT class="item_img" src="/imgs/serviceModal/groups_setting.webp" @click="openGroupSetting" alt="" />
        </div>
      </div>
      <div class="query">
        <nut-input v-model="queryName" :placeholder="t('search_users')" ref="queryNameInput">
          <template #left>
            <iconpark-icon icon-id="majesticonssearch-line" size="1.2rem" class="refresh"></iconpark-icon>
          </template>
        </nut-input>
      </div>
      <div class="list">
        <template v-for="(item, index) in chatitemList1" :key="item.TUsername">
          <div class="list_item" v-longpress="{
            handler: pressHandler,
            params: {
              item,
              index,
              type: (deepObj()['' + item?.deep] || (item?.iskf ==
                1 ? t('official_customer_service') : t('direct_player')))
            }
          }" :class="[(selectedIndex == index && showLongPress) ? 'active' : '', item?.deep !== 0 ? '' : 'guanfang_kefu']">
            <div class="left">
              <div class="img">
                <ImgT class="item_img" :src="`/imgs/head_icons/${item.THeadPhoto ? item.THeadPhoto : 'default'}.webp`"
                  alt="" />
                <div class="msg_number" v-if="item.unreadnums">{{ item.unreadnums }}</div>
              </div>
              <div class="name_type">
                <div class="name">{{ item.TUsername }}</div>
                <span class="indent_type" :class="['type' + item?.deep, item?.iskf ==
                  1 ? 'type0' : '']">{{ deepObj()['' + item?.deep] || (item?.iskf ==
                    1 ? t('official_customer_service') : t('direct_player')) }}</span>
              </div>
            </div>
            <div class="right" v-if="item.type === 'MessageTextContent'">
              <div class="time">{{ formatTime(item.date) }}</div>
              <div class="msg" v-html="initMessage(item.content)"> </div>
            </div>
            <div class="right"
              v-else-if="item.type === 'MessagePicContent' || item.type === 'MessageVideoContent' || item.type === 'MessageMoneyContent'">
              <div class="time">{{ formatTime(item.date) }}</div>
              <div class="msg">{{ item.type === 'MessagePicContent' ? '[' + t('image') + ']' : item.type ===
                'MessageMoneyContent'
                ? '[' + t('transfer') + ']' : '[' + t('video') + ']' }}</div>
            </div>
            <div class="right" v-else-if="item?.deep === 0 || item?.iskf == 1">{{ t('consult_customer_service') }}</div>
            <!-- <iconpark-icon v-if="item.enableflag === 1" class="enableflag" icon-id="tanchuzwpy03" color="#fff" size="1rem" @click.stop="(e: any) => pressHandler(e, 'longPress', { item, index, type: '' })"></iconpark-icon> -->
            <iconpark-icon v-if="item.enableflag === 1" class="enableflag" icon-id="tanchuzwpy03" color="#fff"
              size="1rem"></iconpark-icon>
          </div>
          <div class="pin_line" v-if="item?.deep === 0"></div>
        </template>
      </div>
    </div>
    <!-- 分组弹窗 -->
    <Modal v-model:visible="showGroupSetting" :title="t('group_management')" :zindex="1000">
      <div class="group_list_setting popup_body" v-if="step == 1">
        <div class="title">
          {{ t('group_conversations') }}
        </div>
        <div class="group_list">
          <div class="group_item" v-for="(item, index) in state.groupList" :key="index"
            @click="groupHandler(item, index + 1)">
            <div class="left">
              <ImgT src="/imgs/serviceModal/group_item.webp" alt="" />
              <div class="item_title">{{ item.name }}</div>
            </div>
            <iconpark-icon icon-id="fenzshanxin01" size="1.2rem" class="delete" @click.stop="delGroup(item)"></iconpark-icon>
          </div>
        </div>
        <div class="submit_btn">
          <div height="44px" width="200px" class="submit" @click="addGroup">
            <iconpark-icon icon-id="tongyicontjyhk" size="1.2rem" class="add"></iconpark-icon>
            <span>{{ t('new_group') }}</span>
          </div>
        </div>
      </div>
      <div class="add_group popup_body" v-else-if="step == 2">
        <div class="content">
          <div class="info">{{ t('group_name') }}:</div>
          <nut-input type="text" clearable size="large" max-length="12" v-model="groupName"
            :placeholder="t('group_name')"></nut-input>
          <div class="info">{{ t('included_conversations') }}:</div>
          <div class="add_chat" @click="addUser">
            <iconpark-icon icon-id="dibultktxs04" size="1.2rem" class="add"></iconpark-icon>
            <div class="text">{{ t('add_conversation') }}</div>
          </div>
          <div class="add_chatlist">
            <div class="chatlist" v-for="(item, index) in chatitemIdList" :key="index">
              <div class="item">
                <ImgT class="item_img" :src="`/imgs/head_icons/${item.THeadPhoto ? item.THeadPhoto : 'default'}.webp`"
                  alt="" />
                <div class="name">{{ item.TUsername }}</div>
                <span class="indent_type" :class="['type' + item?.deep, item?.iskf ==
                  1 ? 'type0' : '']">{{ translateText(item) }}</span>
              </div>
              <iconpark-icon class="close" icon-id="tongyiconguanb01" color="#fff" size="1rem"
                @click="delItem(item)"></iconpark-icon>
            </div>
          </div>
          <div class="submit_btn">
            <Btn height="44px" v-shrink-on-click width="140px" class="submit cancel" @click="cancelAddGroup">
              {{ t('cancel') }}</Btn>
            <Btn height="44px" v-shrink-on-click width="140px" class="submit" @click="saveGroup">{{ t('save') }}</Btn>
          </div>
        </div>
      </div>
      <div class="add_group popup_body" v-else>
        <div class="content">
          <nut-input v-model="queryName" :placeholder="t('search_conversation') + '...'">
            <template #left>
              <iconpark-icon icon-id="majesticonssearch-line" size="1.2rem" class="refresh"></iconpark-icon>
            </template>
          </nut-input>
          <div class="add_chatlist">
            <template v-for="(item, index) in chatitemList1" :key="index">
              <div class="chatlist" :class="{ 'selected': IsIteminIdList(item) }" @click="togoItemSelect(item)"
                v-if="(item?.iskf != 1) && item?.deep !== 0 && !item.have && (item?.chatgroupid < 1 || item?.chatgroupid == undefined)">
                <div class="item">
                  <ImgT class="item_img" :src="`/imgs/head_icons/${item.THeadPhoto ? item.THeadPhoto : 'default'}.webp`"
                    alt="" />
                  <div class="name">{{ item.TUsername }}</div>
                </div>
                <span class="indent_type" :class="['type' + item?.deep, item?.iskf ==
                  1 ? 'type0' : '']">{{ deepObj()['' + item?.deep] || (item?.iskf ==
                    1 ? t('official_customer_service') : t('direct_player')) }}</span>
              </div>
            </template>
          </div>
          <div class="submit_btn">
            <Btn height="44px" v-shrink-on-click width="140px" class="submit cancel" @click="closeChatItem">
              {{ t('cancel') }}
            </Btn>
            <Btn height="44px" v-shrink-on-click width="140px" class="submit" @click="saveSelected()">{{ t('save') }}
            </Btn>
          </div>
        </div>
      </div>
    </Modal>
    <!-- 长按弹窗 -->
    <nut-popup class="options_popup" :overlay="true" v-model:visible="showLongPress" :style="popupStyle">
      <div class="popup_box">
        <div class="popup_list" id="popup_list" @click.stop="">
          <div class="item" v-for="(item, index) in popupList" :key="index" :class="longPressactive == index ? 'active' : ''"
            @click="handleChatItem(index)">
            <div class="title">{{ item.title }}</div>
            <iconpark-icon class="close" :icon-id="item.icon" color="#fff" size="1rem"></iconpark-icon>
          </div>
          <div class="show_group_list" id="show_group_list" v-show="showGroupList">
            <div class="item" v-for="(item1, index) in state.groupList" :key="index"
              :class="curLongPressItem?.chatgroupid == item1.id ? 'active' : ''" @click="moveToGroup(index)">
              {{ curLongPressItem?.chatgroupid == item1.id ? '√' : '' }} {{ item1.name }}
            </div>
          </div>
        </div>
      </div>
    </nut-popup>
    <Modal v-model:visible="visible" :title="t('tip')">
      <div class="modal_body">
        <div class="content">
          {{ t('loginTip', { days: Math.ceil(days) }) }}
        </div>
        <Btn height="36px" v-shrink-on-click width="140px" class="submit" @click="visible = false">{{ t('confirm') }}
        </Btn>
      </div>
    </Modal>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, reactive, watch, onMounted, onUnmounted, watchEffect } from 'vue';
import { useRouter, useRoute } from "vue-router";
import Modal from "@/components/Modal.vue";
import usechatHooks from './useHooks.ts';
import useAutoReplyHooks from './useAutoReplyHooks.ts';
import protobuf from 'protobufjs';
import IWebsocket from './chatWS'
import { showToast, showDialog } from "@nutui/nutui";
import { useI18n } from "vue-i18n";
import { Chat } from '@/store/chat';
import { storeToRefs } from 'pinia';
import { i18n } from '@/languages';
import { Page } from '@/store/page';
import pinia from '@/store/index';
import { Local } from '@/utils/storage';
import { isIosWKWebView, isAndroidApp } from "@/utils/publicMethods";

const { t } = useI18n();
const chat = Chat();
const { mutetype } = storeToRefs(chat);
const queryNameInput = ref()
const router = useRouter();
const route = useRoute();
const roleInfo = Local.get('roleInfo') && JSON.parse(Local.get('roleInfo') || '')

const deepObj = (): any => ({
  '-1': t('superior_agent'),
  '1': t('inferior_agent'),
  '0': t('official_customer_service'),
})
const formatTime = (dateTimeStr: any) => {
  const date = new Date(dateTimeStr);
  const now = new Date();
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();

  const nowYear = now.getFullYear();
  const nowMonth = now.getMonth() + 1;
  const nowDay = now.getDate();
  const hours = date.getHours();
  const minutes = date.getMinutes().toString().padStart(2, '0');
  // 今天
  if (year === nowYear && month === nowMonth && day === nowDay) {
    if (hours >= 0 && hours < 6) {
      return `${t('midnight')} ${hours}:${minutes}`;
    } else if (hours >= 6 && hours < 12) {
      return `${t('morning')} ${hours}:${minutes}`;
    } else if (hours === 12) {
      return `${t('noon')} ${hours}:${minutes}`;
    } else if (hours > 12 && hours < 18) {
      return `${t('afternoon')} ${hours}:${minutes}`;
    } else {
      return `${t('evening')} ${hours}:${minutes}`;
    }
  }
  // 昨天
  if (year === nowYear && month === nowMonth && day === nowDay - 1) {
    return `${t('yesterday')} ${hours}:${minutes}`;
  }
  // 更早的日期，原样返回日期时间
  return dateTimeStr;
}

const translateText = (item: any) => {
  return deepObj()['' + item?.deep] || (item?.iskf ==
    1 ? t('official_customer_service') : t('direct_player'))
}

const state: any = reactive({
  routeName: 'chatList',
  root: null,
  deviceID: roleInfo?.id || '',// roleInfo.id,
  requestid: 5000, //请求id
  todeviceid: 2654917, //对方设备ID
  chatitemList: [], // 聊天列表
  groupList: [],   // 分组列表

})
const { getChatlist, getChatMsg13, groupChatitemList, getChatMsg24, getChatMsg12, getListGroup, encodeParams, encodeInput, decodeContent, editchat, searchuser, getChatMsg15, initMessage }: any = usechatHooks(state)
const { getShortcutlist, getShortcutMsg, startTimer }: any = useAutoReplyHooks(state)

const iscocos = ref(true)
// 返回cocos 或者 h5我的
const goBack = () => {
  if (iscocos.value) {
    try {
      if (isAndroidApp()) {
        (window as any).AndroidInterface?.chatBack();
      } else if (isIosWKWebView()) {
        (window as any).webkit.messageHandlers.eventTracker.postMessage({
          eventName: "chat_back",
          params: {}
        });
      } else { //cocos的h5
        window.parent.postMessage({ action: "3rd_back", }, "*");
      }
      Local.set('deviceid', '')
    } catch (error) { }
  } else {
    router.push({ path: '/me', force: true })
  }
}

const msgTypeObj: any = {
  1: 'MessageTextContent',//文字消息
  2: 'MessageMoContent',//表情消息
  3: 'MessagePicContent', //图片
  4: 'MessageVideoContent',//视频
  5: 'MessageMoneyContent'//转账
}
const getChatMsgPublic = (data: any) => {
  const decodeobj2 = decodeContent(data.content, 'MessageOutpute')
  const decodeobj3 = decodeContent(decodeobj2.data, msgTypeObj[decodeobj2.mtype])
  // console.log("onMessage/MessageTextContent output3 ", decodeobj3)
  const getchatId = (id1: any, id2: any) => {
    if (id1 > id2) {
      return id1 + '-' + id2; //大的在前小的在后
    } else {
      return id2 + '-' + id1; //大的在前小的在后
    }
  };
  const messageObj = {
    date: decodeobj2.sendtime,   //时间
    chatid: getchatId(decodeobj2.fromdeviceid, decodeobj2.todeviceid),
    content: decodeobj3.data,   //消息
    type: msgTypeObj[decodeobj2.mtype],
  }
  state.chatitemList = state.chatitemList.map((item: any) => {
    if (item.chatid === messageObj.chatid) {
      return { ...item, ...messageObj };
    }
    return item;
  });
}
// 聊天消息
const getChatMsg2 = (decodeobj1: any, SyncResp: string) => {
  const decodeobj00 = decodeContent(decodeobj1.data, SyncResp);
  // console.log("onMessage/SyncResp output4 ", decodeobj00)
  if (Object.keys(decodeobj00).length > 0) {
    if (Object.keys(decodeobj00.messages).length > 0) {
      // 找出能显示的最新一条消息
      // const lastItem = decodeobj00.messages.find((item: any) => item.cstatus == 1);
      // if (lastItem) {
      //   getChatMsgPublic(lastItem);
      // }
      getChatMsgPublic(decodeobj00.messages[0])
    }
  }
}
const saveGroupLoading = ref(false)

// 搜索
const queryName = ref()
let active = ref(0)
const selectTab = (index: any, item?: any) => {
  active.value = index
  getChatlist(item)
}
const chatitemList1 = computed(() => {
  let chatitemList: any = [...state.chatitemList]
  // 有消息的放上面
  chatitemList = chatitemList?.sort((a: any, b: any) => {
    if (a.unreadnums === undefined) return 1;
    if (b.unreadnums === undefined) return -1;
    return a.unreadnums - b.unreadnums;
  })
  // sort :客服始终排上面面 其他置顶在客服下面置顶
  chatitemList = chatitemList?.sort((a: any, b: any) => {
    if (a.istop === undefined) return 1;
    if (b.istop === undefined) return -1;
    return a.istop - b.istop;
  })
  chatitemList = chatitemList?.sort((a: any, b: any) => {
    if (a.iskf === undefined) return 1;
    if (b.iskf === undefined) return -1;
    return a.iskf - b.iskf;
  })
  chatitemList?.sort((a: any, b: any) => (a.deep === 0 ? -1 : b.deep === 0 ? 1 : 0));
  // 添加对话时识别已有的chatitemIdList
  if (chatitemIdList.value?.length > 0 && step.value != 3) {
    const idsSet = new Set(chatitemIdList.value.map((obj: any) => obj.id));
    chatitemList = chatitemList.map((obj2: any) => ({
      ...obj2,
      have: idsSet.has(obj2.id)
    }));
  }
  console.log(111, chatitemList)
  if (!queryName.value) return chatitemList
  let arr = chatitemList.filter((item: any) => {
    return item.TUsername?.indexOf(queryName.value) != -1
  })
  return arr
})
// 新建分组
const showGroupSetting = ref(false)
const groupName = ref('')
const curEditGroupId = ref('')
const curEditGroupIndex = ref('')
const step = ref(1)
const editGroupItem = ref()
const chatitemIdList: any = ref(groupChatitemList || [])
watch(showGroupSetting, (v) => {
  if (!v) queryName.value = ''
  window.scrollTo(0, 0);
  document.body.scrollTop = 0;
  document.documentElement.scrollTop = 0;
})
watch(queryName, (v) => {
  if (!v && active.value == 0) {
    getChatlist()
  } else {
    if (active.value == 0) {
      searchuser(queryName.value)
    }
  }
})
const openGroupSetting = () => {
  editGroupItem.value = null
  step.value = 1
  groupName.value = ''
  showGroupSetting.value = true
}
const groupHandler = (item: any, index: any) => {
  groupName.value = item.name
  curEditGroupId.value = item.id
  curEditGroupIndex.value = index
  editGroupItem.value = item
  selectTab(index, item)
  step.value = 2
}
const addGroup = () => {
  step.value = 2
  groupName.value = ''
  curEditGroupId.value = ''
  groupChatitemList.value = []
}
// 取消保存分组
const cancelAddGroup = () => {
  step.value = 1
}
// 添加对话
const addUser = () => {
  step.value = 3
  // chatitemIdList.value = []
  selectTab(0)
}
// 选择对话取消
const closeChatItem = () => {
  step.value = 2
  if (curEditGroupId.value) {
    selectTab(curEditGroupIndex.value, editGroupItem.value)
  } else {
    chatitemIdList.value = []
  }
}
// 保持选择对话取消
const saveSelected = () => {
  step.value = 2
  // chatitemIdList.value = chatitemList.value.map((item:any) => chatitemIdList.value.find((obj:any) => obj.id === item.id));
}
// 删除选择的对话
const delItem = (item: any) => {
  chatitemIdList.value = chatitemIdList.value.filter((op: any) => op.id != item.id)
  if (editGroupItem.value && editGroupItem.value.id && editGroupItem.value.id == item.chatgroupid) {
    let it = item
    it.groupid = -1
    editchat(it)
  }
}
// 对话列表选择切换
const togoItemSelect = (item: any) => {
  if (chatitemIdList.value?.find((op: any) => op.id === item.id)) {
    chatitemIdList.value = chatitemIdList.value.filter((op: any) => op.id != item.id)
  } else {
    chatitemIdList.value?.push(item)
  }
}
const IsIteminIdList = (item: any) => {
  return chatitemIdList.value?.find((op: any) => op.id === item.id)
}
// 保存分组
const saveGroup = () => {
  if (!groupName.value.trim()) {
    showToast.fail(t('group_name_required'));
    return
  }
  if (chatitemIdList?.value?.length < 1) {
    showToast.fail(t('group_members_required'));
    return
  }
  state.requestid++;
  const requestid = state.requestid;
  let type = 9; //
  var payload: any = {
    deviceid: state.deviceID,
    sort: 1,
    istop: 2,
    name: groupName.value
  }
  // 编辑分组
  if (editGroupItem.value && editGroupItem.value.id) {
    payload.id = editGroupItem.value.id
    type = 10
  }
  const decodedata = encodeParams(payload, 'ChatGroupModifyReq')
  const encodedRequest = encodeInput(type, requestid, decodedata);
  IWebsocket.sendMessageHandler(encodedRequest)
  showGroupSetting.value = false
}
// 删除分组
const delGroup = (item: any) => {
  showDialog({
    title: t('tip'),
    content: t('confirm_delete'),
    okText: t('confirm'),
    cancelText: t('cancel'),
    onOk: async () => {
      const requestid = state.requestid;
      const type = 11; //
      var payload = {
        deviceid: state.deviceID,
        id: item.id,
        sort: 0,
        istop: 0,
        name: "",
      }
      const decodedata = encodeParams(payload, 'ChatGroupModifyReq')
      const encodedRequest = encodeInput(type, requestid, decodedata);
      IWebsocket.sendMessageHandler(encodedRequest);
    },
  })
}

// 长按功能操作
const curLongPressItem: any = ref({})
const curLongPressIndex: any = ref(0)
const showLongPress = ref(false)
const selectedIndex = ref(0)
const longPress = ref(false)
const popupHeight = ref(0);
const popupStyle = reactive({
  top: '0px',
});
const pressHandler = (location: any, action: any, { item, index, type }: any) => { //点击或者长按
  console.log('index,item', index, item.TUsername)
  let idx = chatitemList1.value.findIndex((currentItem: any) => currentItem.TUsername === item.TUsername)
  showGroupList.value = false
  if (action === 'click') {
    selectUser(item, type)
    return
  }
  let pointerY = location.clientY
  if (item?.deep !== 0 && item?.iskf != 1) {
    curLongPressItem.value = item
    curLongPressIndex.value = idx
    showLongPress.value = true
    selectedIndex.value = idx

    longPress.value = true

    setTimeout(() => {
      // 适配弹框位置
      let el = document.getElementById('popup_list') as HTMLElement
      if (!el) return
      popupHeight.value = el.offsetHeight;
      const windowHeight = window.innerHeight;
      let top = pointerY + 50
      let top1 = (windowHeight - popupHeight.value); //超出底部 时，top的值
      if (pointerY > top1) top = top1 - 10
      popupStyle.top = top + 'px'
    }, 0)
    setTimeout(() => { longPress.value = false }, 100)
  }
}
const popupList = computed(() => {
  if (chatitemList1.value.length == 0) return []
  let item = chatitemList1.value.find((currentItem: any) => currentItem.TUsername === curLongPressItem.value.TUsername)
  let arr = [
    {
      title: item?.istop === 1 ? t('cancel_top') : t('top'),
      icon: 'tanchuzwpy01'
    },
    // {
    //   title: item?.unreadnums ? '未读' : '已读',
    //   icon: 'tanchuzwpy02'
    // },
    {
      title: item?.enableflag === 1 ? t('unblock') : t('block'),
      icon: item?.enableflag === 1 ? 'tanchuzwpy03' : 'tanchuzwpy06'
    },
    {
      title: t('move_to_group'),
      icon: 'tanchuzwpy04'
    },
  ]
  return arr
})
const longPressactive = ref(0)
const showGroupList = ref(false)
const handleChatItem = (index: any) => {
  let item = curLongPressItem.value
  longPressactive.value = index
  item.groupid = active.value !== 0 ? (state.groupList[active.value !== 0 ? active.value - 1 : 0]?.id) : 0
  switch (index) {
    case 0:// 置顶
      item.istop = item.istop === 1 ? 6 : 1
      editchat(item)
      break
    // case 1:// 未读
    //   alreadread(item)
    //   break
    case 1:// 屏蔽
      item.enableflag = item.enableflag === 1 ? 7 : 1
      editchat(item)
      break
    case 2: // 移动分组
      showGroupList.value = !showGroupList.value
      setTimeout(() => {
        // 适配展开分组列表
        let el2 = document.getElementById('show_group_list') as HTMLElement
        const windowHeight = window.innerHeight;
        if (!el2) return
        let top2 = 0
        let el2Height = el2.offsetHeight;
        let el2top = (windowHeight - el2Height) / 2; //超出底部 时，top的值
        if (el2top + el2Height > windowHeight) {
          top2 = windowHeight - el2Height - 10
          el2.style.position = 'fixed!important'
          el2.style.top = top2 + 'px'
        }
      }, 0);
      break
    default:
      break
  }
}
// 移动到某分组
const moveToGroup = (index: any) => {
  let item = curLongPressItem.value
  item.groupid = state.groupList[index]?.id
  editchat(item)
}
const closePop = () => {
  showGroupList.value = false
  showLongPress.value = false
}
// 点击进入对话
const selectUser = (item: any, type: any) => {
  if (showLongPress.value) return
  queryNameInput.value?.blur()
  Local.set('toUserData', item)
  setTimeout(() => {
    router.push({
      path: '/chatRoom',
      query: {
        type,
      }
    })
  }, 800);
}

//订阅
const visible = ref(false)
const days = ref(0)
const onMessage: any = async (buffer: any) => {
  const decodeobj1 = decodeContent(buffer, 'Output');
  console.log("onMessage/Output output0 ", decodeobj1)
  if (decodeobj1.code == '10020') {// 弹框形式提示禁止登录
    days.value = mutetype.value.days
    visible.value = true
    return
  }
  if (decodeobj1.code == '10022') {
    showToast.fail(t('delete_group_tip'));
    return
  }
  if (decodeobj1.code && decodeobj1.code > 1000) {
    showToast.fail(t(decodeobj1.code));
    return;
  }
  switch (decodeobj1.type) {
    case 1://open成功后再获取数据
      getListGroup()
      getChatlist()
      getShortcutlist()
      break;
    case 4:
      getChatlist()
      // 收到新消息 
      startTimer(decodeobj1)
      break;
    case 13:
      getChatMsg13(decodeobj1, active.value)
      break;
    case 8:
      getChatMsg2(decodeobj1, 'SyncResp')  // 保存循环获取的第一条消息
      break;
    case 10:
    case 9:
      // 添加分组成功后，循环加入对话
      const decodeobj00 = decodeContent(decodeobj1.data, 'ChatGroupModifyRsp');
      saveGroupLoading.value = true
      if (chatitemIdList?.value?.length) {
        chatitemIdList.value.forEach((item: any) => {
          item.groupid = decodeobj1.type == 9 ? decodeobj00.id : editGroupItem.value.id
          editchat(item)
        })
      }
      getListGroup()
      setTimeout(() => {
        saveGroupLoading.value = false
        selectTab(0)
      }, 500)
      showToast.text(t('operation_success'))//分组列表保存回执
      break;
    case 11:
      selectTab(0)
      getListGroup()
      showToast.text(t('operation_success')) //分组列表删除回执
      break;
    case 12:
      getChatMsg12(decodeobj1)// 保存分组列表
      break;
    case 15:
      getChatMsg15(decodeobj1)
      break;
    case 19://快捷列表数据
      getShortcutMsg(decodeobj1)
      break;
    case 24:
      getChatMsg24(decodeobj1)// 获取客服聊天列表
      break;
    case 14://编辑chatitem回执
      let item = active.value !== 0 ? state.groupList[active.value - 1] : ''
      if (!saveGroupLoading.value) { // 分组循环添加对话过程中不请求列表
        getChatlist(item)
      }
      showToast.text(t('operation_success'))
      closePop()
      break;
    case 27://已读
      let item2 = active.value !== 0 ? state.groupList[active.value - 1] : ''
      if (!saveGroupLoading.value) { // 分组循环添加对话过程中不请求列表
        getChatlist(item2)
      }
      // showToast.text(t('operation_success'))
      closePop()
      break;
    default:
      break;
  }
}
// 初始化相关
const setLang = async (v: any) => {
  let langObj: any = {
    'en-US': 'en-US',
    en: 'en-US',
    'en-AU': 'en-US',
    zh: 'zh-CN',
    'zh-CN': 'zh-CN',
    vi: 'vi-VN',
    'vi-VN': 'vi-VN',
    vn: 'vi-VN'
  }
  if (v) {
    i18n.global.locale.value = langObj[v]
    await Page(pinia).setLang(v)
  } else {
    let lang = langObj[navigator.language]
    i18n.global.locale.value = lang || 'vi-VN'
    await Page(pinia).setLang(lang || 'vn')
  }
}
watchEffect(() => {
  let lang = route.query.lang
  if (lang) {
    setTimeout(() => {
      if (route.query.lang) setLang(lang)
    }, 0);
  }
})
const onOpen = () => {
  let token = Local.get('user')?.token || Local.get('token')
  const type = 1; // PT_SIGN_IN
  const requestid = 5000;
  const singin = {
    deviceid: state.deviceID,//用户的roleid
    userid: state.deviceID,//用户的roleid
    token,// Local.get('user').token,//后期从另外一个项目中获取
  }
  const data = encodeParams(singin, 'SignInInput')
  const params = {
    type: type,
    requestid: requestid,
    data: data,
  };
  const encodedRequest = encodeParams(params, 'Input')
  IWebsocket.sendMessageHandler(encodedRequest);
}
const init = async () => {
  iscocos.value = Local.get('iscocos') === false ? false : true // 从/me进来时存了false
  // console.log(33333333336, route.query, route.query.lang)
  let deviceid = route.query.device_id || Local.get('deviceid')
  if (iscocos.value && deviceid) { //其他地方进来
    state.deviceID = Number(deviceid)
    Local.set('deviceid', deviceid)
    Local.set('token', route.query.token)
    chat.getConfig() // 获取角色
  } else {
    const roleInfo = Local.get('roleInfo') && JSON.parse(Local.get('roleInfo') || '')
    state.deviceID = Number(roleInfo?.id || Local.get('deviceid'))

    Local.set('deviceid', state.deviceID)
    chat.getConfig() // 获取角色
  }
  document.documentElement.style.overflow = 'hidden'
  document.body.style.overflow = 'hidden';
  if (IWebsocket.instance == null) {
    await IWebsocket.conectWebsocket()
  }
  state.root = await protobuf.load('/connect.ext.proto');
  onOpen()
  IWebsocket.resgisterHandler(onMessage)
}
const handleFun = () => {
  if (document.visibilityState === 'visible') {
    window.location.reload();
  }
}
onMounted(async () => {
  init()
  // 息屏重连
  document.addEventListener('visibilitychange', handleFun);
})
onUnmounted(() => {
  document.documentElement.style.overflow = 'visible'
  document.body.style.overflow = 'visible';
  const containsField = ['/shortcut', '/chatRoom', '/friendsList'].includes(route.path);
  if (!containsField) {
    IWebsocket.close()
    IWebsocket.instance = null
  }
  document.removeEventListener('visibilitychange', handleFun)
})
</script>

<style lang="scss" scoped>
.chat_list {
  padding-top: constant(safe-area-inset-top);
  padding-top: env(safe-area-inset-top);
}

.head {
  position: fixed;
  width: 100%;
  height: 55px;
  background-color: #361e79;
  z-index: 1;

  .close {
    z-index: 6;
    width: 38px;
    height: 38px;
  }
}

.section {
  margin-top: 10px;
  padding: 0 10px 0;
  color: #8e82c2;
  margin-top: 65px;

  .groups {
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
    height: 36px;
    flex-grow: 0;
    padding: 5px 7.6px 5px 6px;
    border-radius: 12px;
    box-shadow: 0 1px 1px 0 rgba(0, 0, 0, 0.39), 0 2px 2px 0 rgba(0, 0, 0, 0.34), 0 5px 3px 0 rgba(0, 0, 0, 0.2), 0 8px 3px 0 rgba(0, 0, 0, 0.06), 0 13px 3px 0 rgba(0, 0, 0, 0.01);
    background-image: radial-gradient(circle at 50% 0%, #4c36b3 0%, #3a2786 100%, #3c279a 0%);

    .groups_tabs {
      width: 100%;
      overflow: hidden;

      .scroll-view {

        .item {
          display: inline-block;
          margin: 4px;
          font-size: 14px;
          color: #87a1ce;
          padding: 4px 10px;

          &.active {
            color: #fff;
            background: url(/imgs/home/btn_bg.webp) no-repeat;
            background-size: 100% 100%;
          }
        }
      }
    }

    .group_setting {
      margin-left: 4px;
      padding: 0 5px;
      border-left: 1px solid #201844;
      display: flex;
      align-items: center;
    }
  }

  .query {
    margin-bottom: 10px;

    &:deep(.nut-input) {
      height: 36px;
      padding: 8px;
      border-radius: 8px;
      box-shadow: inset 0 4px 4px 0 rgba(0, 0, 0, 0.25);
      border: solid 1px #322c59;
      background: radial-gradient(circle at 50% 11%, #361e79, #202137 97%) !important;

      .nut-input-box {
        align-items: center;
      }

      input {
        &::placeholder {
          color: #8d84c5;
        }
      }
    }
  }

  .list {
    height: calc(100vh - 160px);
    overflow-y: auto;
    padding-bottom: 10px;

    .guanfang_kefu {
      background: url(/imgs/serviceModal/kefu_bg.webp) no-repeat !important;
      background-size: cover !important;

      .right {
        font-size: 12px;
        text-align: right;
        color: #a2a5de;
        line-height: 40px;
      }
    }

    .pin_line {
      width: 355px;
      height: 1px;
      margin: 16px 0;
      background-color: #201844;
      display: none;

      &:last-of-type {
        display: block;
      }
    }

    .list_item {
      box-sizing: border-box;
      position: relative;
      padding: 10px;
      display: flex;
      justify-content: space-between;
      height: 60px;
      border-radius: 5px;
      background: url(/imgs/serviceModal/list_item_bg.webp) no-repeat;
      background-size: cover;
      margin-top: 10px;

      &.active {
        filter: brightness(80%) grayscale(30%);
      }

      .left {
        display: flex;

        .img {
          width: 40px;
          position: relative;

          .item_img {
            width: 40px;
            height: 40px;
          }

          .msg_number {
            position: absolute;
            top: 0;
            right: 0;
            border: 1px solid #ccc;
            background: red;
            border-radius: 50%;
            width: 14px;
            height: 14px;
            font-size: 10px;
            color: #fff;
            text-align: center;
            line-height: 14px;
          }
        }

        .name_type {
          margin-left: 10px;
          color: #fff;
          min-width: 60px;
          display: flex;
          flex-direction: column;
          justify-content: space-between;
          align-items: start;

          .name {
            overflow: hidden;
            white-space: nowrap;
            text-overflow: ellipsis;
            max-width: 80px;
          }
        }
      }

      .right {
        font-size: 12px;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        line-height: 1;

        .time {
          text-align: right;
          margin-right: 20px;
        }

        .msg {
          width: 200px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
          text-align: right;
        }
      }

      .enableflag {
        position: absolute;
        right: 10px;
      }
    }
  }

}

.indent_type {
  display: inline-block;
  font-size: 12px;
  line-height: 12px;
  border-radius: 20px;
  padding: 3px 4px;
  max-width: 80px;
  overflow: hidden;
  text-wrap: nowrap;
  white-space: nowrap;
  text-overflow: ellipsis;
  border-image-slice: 1;
  border-image-source: linear-gradient(to bottom, #6bcdff 0%, #5e99ff 103%);
  background-image: linear-gradient(88deg, #12b8ff 0%, #1266ff 99%), linear-gradient(to bottom, #6bcdff 0%, #5e99ff 103%);

  &.type0 {
    border-image-source: linear-gradient(to bottom, #fff 0%, #8cacff 103%);
    background-image: linear-gradient(to right, #4c36b3 0%, #3c279a 100%), linear-gradient(to bottom, #fff 0%, #8cacff 103%);
  }

  &.type-1 {
    border-image-source: linear-gradient(to bottom, #ffc38e 0%, #ff7b4c 103%);
    background-image: linear-gradient(88deg, #f92 0%, #da4212 99%), linear-gradient(to bottom, #ffc38e 0%, #ff7b4c 103%);
  }

  &.type1 {
    border-image-source: linear-gradient(to bottom, #ffc38e 0%, #ff7b4c 103%);
    background-image: linear-gradient(88deg, #f92 0%, #da4212 99%), linear-gradient(to bottom, #ffc38e 0%, #ff7b4c 103%);
  }

  // &.type3 {
  //   border-image-source: linear-gradient(to bottom, #ff8dbf 0%, #ff6783 103%);
  //   background-image: linear-gradient(88deg, #ff52a5 0%, #ff264d 99%), linear-gradient(to bottom, #ff8dbf 0%, #ff6783 103%);
  // }

  // &.type4 {
  //   border-image-source: linear-gradient(to bottom, #fff 0%, #8cacff 103%);
  //   background-image: linear-gradient(to right, #4c36b3 0%, #3c279a 100%), linear-gradient(to bottom, #fff 0%, #8cacff 103%);
  // }
}

.group_list_setting.popup_body {
  display: flex;
  flex-direction: column;
  align-items: center;

  .title {
    width: 100%;
    height: 36px;
    display: flex;
    justify-content: center;
    align-items: center;
    background: #1C0F43;
  }

  .group_list {
    width: 100%;
    color: #c0c2db;

    .group_item {
      width: 100%;
      padding: 10px 20px;
      display: flex;
      align-items: center;
      justify-content: space-between;

      .left {
        display: flex;
        align-items: center;

        img {
          margin-top: 6px;
        }

        .item_title {
          margin-left: 10px;
          max-width: 200px;
          white-space: nowrap;
          text-overflow: ellipsis;
          overflow: hidden;
        }
      }
    }
  }

  .submit_btn {
    display: flex;
    align-items: center;
    justify-content: center;
    margin: 20px auto 10px;
    font-size: 16px;
    border: 0;
    width: 200px;
    height: 43px;
    color: var(--c-bg-6);
    border-radius: 12px;
    background: url(/imgs/payment/sub_btn.webp) center no-repeat;
    background-size: cover;

    .submit {
      display: flex;
      align-items: center;
      justify-content: center;
      color: #fff;

      .add {
        margin-right: 5px;
      }
    }

    .cancel {}
  }

}

.add_group {
  color: #fff;

  .content {
    padding: 10px 20px 0;

    .info {
      padding: 10px 0;
    }

    .add_chat {
      color: #9993C6;
      display: flex;
      align-items: center;
      padding: 8px;
      border-radius: 8px;
      background-image: linear-gradient(to bottom, #3A2888 100%, #3A2888 0%), linear-gradient(to right, #3A2888, #3A2888);

      .add {
        margin-right: 10px;
      }
    }

    .add_chatlist {
      .chatlist {
        padding: 10px 0 4px;
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1px solid #201844;

        &.selected {
          background: #2F1D7D;
        }

        &:nth-child(1) {
          border-top-left-radius: 10px;
          border-top-right-radius: 10px;
        }

        .item {
          display: flex;
          align-items: center;

          .item_img {
            width: 30px;
            height: 30px;
          }

          .name {
            padding: 0 10px;
          }

        }
      }
    }

    .submit_btn {
      width: 100%;
      padding: 24px 0;
      display: flex;
      justify-content: space-around;
    }
  }

  .nut-textarea {
    box-shadow: 0px 4px 4px 0px #00000040 inset;
    border-radius: 8px;
    border-bottom: unset;
    display: flex;
    justify-content: center;
    background: #27155C;
    background-blend-mode: overlay;
    padding: 10px;
    background: radial-gradient(50% 208.33% at 50% 50%, rgba(126, 126, 126, 0.32) 0%, rgba(21, 21, 21, 0.32) 100%);
    background: linear-gradient(180deg, rgba(0, 0, 0, 0.02) 0%, rgba(0, 0, 0, 0.1) 100%);

    &:deep(.input-text) {
      text-align: center !important;
    }

    &:deep(.nut-textarea__textarea) {
      color: #ffffff;

      &::placeholder {
        color: #87a1ce;

      }
    }
  }

  .nut-input {
    width: 100%;
    background: #27155C;
    border: 1px solid #322c59;
    border-radius: 8px;
    padding: 9px 8px;
  }
}

:deep(.nut-popup) {
  // width: 100%;
  overflow: unset;
  background: transparent;
  display: flex;
  justify-content: center;
  align-items: center;

}

.popup_box {

  .popup_list {
    position: relative;
    width: 126px;
    border-radius: 10px;
    box-shadow: 0 6px 8px 0 #1a113f;
    background-color: #372487;

    .item {
      font-size: 14px;
      color: #fff;
      height: 32px;
      padding: 6px 12px;
      background-color: #412d97;
      margin: 2px 0 0;
      display: flex;
      justify-content: space-between;

      &:nth-child(1) {
        margin: 0 0 6px;
      }

      &.active {
        background-color: #372487;
      }

      .title {
        width: 100%;
        white-space: nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
      }
    }

    .show_group_list {
      position: absolute;
      width: 100px;
      bottom: -30px;
      right: -110px;
      color: #fff;
      border-radius: 10px;
      overflow: hidden;
      background-color: #301f77;

      .item {
        background-color: #412d97;
        height: 32px;
        padding: 6px 0 0 10px;
        overflow: hidden;
        width: 100px;
        text-overflow: ellipsis;
        white-space: nowrap;


        &:nth-child(1) {
          margin: 0;
        }

        &.active {
          background-color: #301f77;
        }
      }
    }
  }



}

:deep() {
  .nut-navbar {
    padding-top: 0 !important;

    .nut-navbar__left,
    .right-handler {
      color: #fff;
    }
  }
}

.modal_body {
  height: 100%;
  min-height: 150px;
  padding: 20px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}

:deep(.nut-overlay) {
  background: unset
}
</style>